<template>
  <view class="page-content flex-col">
    <u-navbar :is-back="false" title="">
      <view
        class="slot-wrap flex-row justify-between items-center"
        style="display: flex; width: 100%"
      >
        <view class="flex-row justify-between items-center" style="gap: 10rpx">
          <image
            src="/static/common/back.png"
            style="height: 48rpx; width: 48rpx"
            @click="handleback"
          ></image>
          <u-image
            :src="formdata.avatar.split(',')[0]"
            height="48rpx"
            width="48rpx"
            shape="circle"
            @click="
              handleLinkTo(
                `/page_index/me/components/user-detail/user-detail?id=${formdata.publisherId}`
              )
            "
          />
          <view class="nickname">
            {{ formdata.nickName }}
          </view>
          <block v-if="userinfo.id && userinfo.id != formdata.publisherId">
            <view
              v-if="!isGuanzhu"
              class="guanzhu"
              @click="addFans(formdata.publisherId)"
            >
              关注
            </view>
            <view
              v-else
              class="guanzhu"
              style="background: #f4f4f4"
              @click="delFans(fansdetail.id)"
            >
              已关注
            </view>
          </block>
        </view>
        <view class="header-bar-right">
          <button open-type="share" class="share-btn">
            <!-- <image src="/static/common/edit-icon.png" style="height: 40rpx;width: 40rpx;" mode=""></image> -->
          </button>
        </view>
      </view>
    </u-navbar>
    <view class="detail">
      <view class="wrap">
        <u-swiper :list="list" height="712"></u-swiper>
      </view>
      <view class="title mt-16">
        {{ formdata.title }}
      </view>
      <view class="title mt-16">
        {{ formdata.content }}
      </view>
      <view class="publish-time mt-10">
        {{ formdata.createTime }}
      </view>

      <view class="comments">
        <view class="mt-7" v-for="(item, index) in commentsList" :key="index">
          <view class="flex-row items-center">
            <view class="flex-row flex-1 group_4">
              <u-image
                height="72rpx"
                width="72rpx"
                shape="circle"
                :src="item.avatar && item.avatar.split(',')[0]"
                @click="
                  handleLinkTo(
                    `/page_index/me/components/user-detail/user-detail?id=${item.commentUserId}`
                  )
                "
              />
              <view class="ml-10 flex-col items-start flex-1 self-center">
                <text
                  class="font_2"
                  @click="handleReply(item, null, index, item.id)"
                  >{{ item.nickName || "--" }}</text
                >
                <text class="font_3 mt-7">{{ item.content || "--" }}</text>
                <text class="font_4 text_5">{{ item.createTime || "--" }}</text>
                <text
                  class="text_9"
                  v-if="item.number > 0 && commentsListSec[index].length === 0"
                  @click="getCommentListTwo(index, item.id)"
                  >展开{{ item.number }}条评论</text
                >
              </view>
            </view>
            <view class="ml-20 flex-col items-center shrink-0">
              <!-- <u-rate
                active-icon="heart-fill"
                inactive-icon="heart"
                :count="1"
                @change="handleChangeLike"
                size="40"
              ></u-rate> -->
              <!-- <text class="font_5 text_6 mt-7">{{ item.likeCount }}</text> -->
            </view>
          </view>
          <view class="two-level-commons">
            <view
              class="flex-row items-center"
              v-for="(itemt, indext) in commentsListSec[index]"
              :key="indext"
            >
              <view class="flex-row flex-1 group_4">
                <u-image
                  height="72rpx"
                  width="72rpx"
                  shape="circle"
                  :src="itemt.avatar && itemt.avatar.split(',')[0]"
                  @click="
                    handleLinkTo(
                      `/page_index/me/components/user-detail/user-detail?id=${itemt.sendUserId}`
                    )
                  "
                />
                <view class="ml-10 flex-col items-start flex-1 self-center">
                  <view
                    class="font_2"
                    @click="handleReply(item, itemt, -1, -1)"
                    >{{ itemt.nickName || "--" }}</view
                  >
                  <text class="font_3 mt-7">
                    <text style="color: #000">回复</text>
                    <text style="color: #17b3f5">{{
                      itemt.rnickName || "--"
                    }}</text>
                    {{ itemt.content }}
                  </text>
                  <text class="font_4 text_5">{{
                    itemt.createTime || "--"
                  }}</text>
                </view>
              </view>
              <view class="ml-20 flex-col items-center shrink-0">
                <!-- <u-rate
                  active-icon="heart-fill"
                  inactive-icon="heart"
                  :count="1"
                  @change="handleChangeLike"
                  size="40"
                ></u-rate> -->
                <!-- <text class="font_5 text_6 mt-7">{{ itemt.likeCount }}</text> -->
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="publish-comment flex-row items-center" style="gap: 34rpx">
      <view
        style="
          width: 100%;
          padding: 14rpx 40rpx;
          border-radius: 80rpx;
          background-color: #f4f4f4;
          box-sizing: border-box;
					padding-bottom: 32rpx;
        "
      >
        <u-input
          height="64rpx"
          disabled
          @click="changeFocus(true)"
          :placeholder="commentPlaceholder"
        />
      </view>
      <view class="flex-row items-center">
        <u-icon name="chat" size="40" color="#999999"></u-icon>
        <view style="white-space: nowrap; color: #999999">{{
          formdata.commentNum
        }}</view>
      </view>
      <view class="flex-row items-center">
        <u-rate
          v-model="collectNum"
          :count="1"
          @change="handleChangeCollect"
          size="40"
          active-color="#FCD610"
          inactive-color="#999999"
        ></u-rate>
        <view style="white-space: nowrap; color: #999999">{{
          formdata.collectionNum
        }}</view>
      </view>
      <view class="flex-row items-center">
        <u-rate
          v-model="likeNum"
          active-icon="heart-fill"
          inactive-icon="heart"
          :count="1"
          @change="handleChangeLike"
          size="40"
          inactive-color="#999999"
        ></u-rate>
        <view style="white-space: nowrap; color: #999999">{{
          formdata.likeCount
        }}</view>
      </view>
    </view>
    <u-popup v-model="showComment" @close="changeFocus(false)" mode="bottom">
      <view
        class="flex-row justify-between"
        style="
          width: 100%;
          padding: 14rpx 32rpx;
          box-sizing: border-box;
          gap: 10rpx;
        "
      >
        <view
          style="
            flex: 1;
            border-radius: 40rpx;
            background-color: #f4f4f4;
            padding: 10rpx 32rpx;
          "
        >
          <u-input
            v-model="commentdata.content"
            type="textarea"
            maxHeight="260"
            maxlength="1000"
            :focus="focus"
            :show-confirmbar="false"
            :clearable="false"
            cursor-spacing="70"
            :placeholder="commentPlaceholder"
          />
        </view>
        <view class="publish-btn" @click="addComment"> 发布 </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import chongyouquan from "../../../api/chongyouquan";
import mine from "../../../api/mine";
export default {
  data() {
    return {
      list: [],
      formdata: {
        city: "",
        title: "",
        content: "",
        location: "",
        publisher: "",
        publisherId: "",
        picture: "",
        createTime: "",
        likeCount: 0,
        collectionNum: 0,
        commentNum: 0,
        nickName: "",
      },
      commentsList: [],
      commentsListSec: [],
      collectNum: 0,
      likeNum: 0,
      commentPlaceholder: "输入评论",
      commentdata: {
        receiverUserId: "",
        receiver: "",
        postCommentId: "",
        content: "",
        postId: "",
      },
      userinfo: "",
      showComment: false,
      focus: false,
      isGuanzhu: false,
      fansdetail: null,
      currentIndex: -1,
      currentId: -1,
    };
  },
  watch: {
    showComment: function (newvalue, oldvalue) {
      if (newvalue === false) {
        this.commentdata.content = "";
        this.commentdata.postCommentId = "";
        this.commentdata.receiverUserId = "";
        this.commentdata.receiver = "";
      }
    },
  },
  onLoad(option) {
    if (option.id) {
      this.getDetail(option.id);
      this.commentdata.postId = option.id;
      this.getCommentListOne();
    }
    this.userinfo = uni.getStorageSync("userinfo");
  },
  onShareAppMessage(e) {
    let shareobj = {
      title: this.formdata.title, //分享的标题
      path:
        "/pages/quan/pet-circle-detail/pet-circle-detail?id=" +
        this.formdata.id, //好友点击分享之后跳转的页面
      imageUrl: this.list[0], //分享的图片  支持PNG及JPG。显示图片长宽比是 5:4。
      // imageUrl: this.shareImg, //内容图片
    };
    return shareobj; //一定要返回对象
  },
  methods: {
    handleback() {
      uni.navigateBack();
    },
    getDetail(id) {
      chongyouquan.getCYQuanDetailById(id).then((res) => {
        if (res.code === 200) {
          this.formdata = res.data;
          this.list = res.data.picture && res.data.picture.split(",");
          this.getCollectTieziList();
          this.getLikeTieziList();
          this.getFans();
        }
      });
    },
    getCollectTieziList() {
      mine
        .getCollectOrLickTieziList({
          userId: this.userinfo.id,
          type: 1,
        })
        .then((res) => {
          if (res.code === 200) {
            res.rows?.forEach((item) => {
              if (item.postId === this.formdata.id) this.collectNum = 1;
            });
          }
        });
    },
    getLikeTieziList() {
      mine
        .getCollectOrLickTieziList({
          userId: this.userinfo.id,
          type: 2,
        })
        .then((res) => {
          if (res.code === 200) {
            res.rows?.forEach((item) => {
              if (item.postId === this.formdata.id) this.likeNum = 1;
            });
          }
        });
    },
    handleChangeCollect(e) {
      if (e === 0)
        chongyouquan
          .addOrDelCollect(this.formdata.id, 2)
          .then((res) => {
            if (res.code === 200) {
              uni.showToast({
                title: "已取消",
                icon: "none",
              });
              this.formdata.collectionNum--;
            } else throw Error();
          })
          .catch((err) => {
            uni.showToast({
              title: "取消失败",
              icon: "none",
            });
          });
      else
        chongyouquan
          .addOrDelCollect(this.formdata.id, 1)
          .then((res) => {
            if (res.code === 200) {
              uni.showToast({
                title: "已收藏",
                icon: "none",
              });
              this.formdata.collectionNum++;
            } else throw Error();
          })
          .catch((err) => {
            uni.showToast({
              title: "收藏失败",
              icon: "none",
            });
          });
    },
    handleChangeLike(e) {
      if (e === 0)
        chongyouquan
          .addOrDelLike(this.formdata.id, 2)
          .then((res) => {
            if (res.code === 200) {
              this.formdata.likeCount--;
            } else throw Error();
          })
          .catch((err) => {
            uni.showToast({
              title: "取消失败",
              icon: "none",
            });
          });
      else
        chongyouquan
          .addOrDelLike(this.formdata.id, 1)
          .then((res) => {
            if (res.code === 200) {
              this.formdata.likeCount++;
            } else throw Error();
          })
          .catch((err) => {
            uni.showToast({
              title: "点赞失败",
              icon: "none",
            });
          });
    },
    handleReply(item, item2, index, id) {
      this.commentPlaceholder = "回复 @" + item.nickName;
      this.commentdata.postCommentId = item.id;
      this.commentdata.receiverUserId = item.commentUserId;
      this.commentdata.receiver = item.nickName;
      if (index >= 0 || id >= 0) {
        this.currentIndex = index;
        this.currentId = id;
      }

      if (item2) {
        this.commentPlaceholder = "回复 @" + item2.nickName;
        this.commentdata.receiverUserId = item2.sendUserId;
        this.commentdata.receiver = item2.nickName;
      }
      this.changeFocus(true);
    },
    changeFocus(val) {
      this.showComment = val;
      if (val) {
        this.focus = false;
        this.$nextTick(() => {
          this.focus = true;
        });
      }
    },
    addComment() {
      uni.showLoading({
        title: "发送中",
      });

      if (this.commentdata.content !== "") {
        let newform = JSON.parse(JSON.stringify(this.commentdata));
        if (newform.receiverUserId) {
          delete newform.postId;
          newform.sendUserId = this.userinfo.id;
          chongyouquan
            .addSecondaryComment(newform)
            .then((res) => {
              uni.hideLoading();
              if (res.code === 200) {
                chongyouquan.getCommentListTwo(this.currentId).then((res) => {
                  if (res.code === 200) {
                    if (this.commentsListSec[this.currentIndex].length > 0) {
                      this.commentsListSec[this.currentIndex].push(
                        res.rows[res.rows.length - 1]
                      );
                    } else {
                      this.commentsListSec[this.currentIndex].push(...res.rows);
                    }
                  }
                });
                this.commentdata.content = "";
                this.commentdata.receiverUserId = "";
                this.commentdata.postCommentId = "";
                this.commentdata.receiver = "";
                this.showComment = false;
              } else throw Error();
            })
            .catch((err) => {
              uni.hideLoading();
              uni.showToast({
                title: "发送失败",
                icon: "none",
              });
            });
        } else {
          delete newform.receiverUserId;
          delete newform.postCommentId;
          delete newform.receiver;
          newform["commentUserId"] = this.userinfo.id;
          chongyouquan
            .addComment(newform)
            .then((res) => {
              uni.hideLoading();
              if (res.code === 200) {
                this.getCommentListOne();
                this.commentdata.content = "";
                this.commentdata.receiverUserId = "";
                this.commentdata.postCommentId = "";
                this.commentdata.receiver = "";
                this.showComment = false;
              } else throw Error();
            })
            .catch((err) => {
              uni.hideLoading();
              uni.showToast({
                title: "发送失败",
                icon: "none",
              });
            });
        }
      } else {
        uni.showToast({
          title: "请输入内容",
          icon: "none",
        });
      }
    },
    getCommentListOne() {
      chongyouquan.getCommentListOne(this.commentdata.postId).then((res) => {
        if (res.code === 200) {
          this.commentsList = res.rows;
          if (res.rows.length > 0) {
            res.rows.forEach((item) => {
              this.commentsListSec.push([]);
            });
          }
        }
      });
    },
    getCommentListTwo(index, id) {
      this.currentIndex = index;
      this.currentId = id;
      chongyouquan.getCommentListTwo(id).then((res) => {
        if (res.code === 200) {
          this.commentsListSec[index].push(...res.rows);
        }
      });
    },
    addFans(followId) {
      const data = {
        followId: followId,
        userId: this.userinfo.id,
      };
      chongyouquan.addFans(data).then((res) => {
        if (res.code == 200) {
          uni.showToast({
            title: "已关注",
          });
          this.isGuanzhu = !this.isGuanzhu;
        }
      });
    },
    getFans() {
      mine
        .getFansList({
          followId: this.formdata.publisherId,
        })
        .then((res) => {
          if (res.code === 200) {
            for (var i = 0; i < res.rows.length; i++) {
              const item = res.rows[i];
              if (item.userId == this.userinfo.id) {
                this.isGuanzhu = true;
                this.fansdetail = item;
                break;
              }
            }
          } else {
            throw Error();
          }
        });
    },
    delFans(id) {
      chongyouquan.delFans(id).then((res) => {
        if (res.code == 200) {
          uni.showToast({
            title: "已取消关注",
            icon: "none",
          });
          this.isGuanzhu = !this.isGuanzhu;
        }
      });
    },
    handleLinkTo(url) {
      uni.navigateTo({
        url: `${url}`,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background-color: #f6f6f6;

  /deep/ .u-navbar-content-title {
    display: none;
  }

  /deep/ .u-indicator-item-round-active {
    background: #fcd610;
  }

  .slot-wrap {
    padding: 0 32rpx;

    .nickname {
      width: 160rpx;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .guanzhu {
      background: #fcd610;
      border-radius: 16rpx;
      height: 48rpx;
      font-weight: bold;
      font-size: 24rpx;
      color: #000000;
      text-align: center;
      padding: 8rpx 32rpx;
    }

    .header-bar-right {
      .share-btn {
        border: 0rpx;
        background-image: url("/static/common/edit-icon.png");
        background-size: cover;
        background-position: center center;
        height: 40rpx;
        width: 40rpx;
        padding: 0;
        margin: 0;
      }
    }
  }

  .detail {
    padding: 0 32rpx;
    background-color: #f6f6f6;
    height: 100%;
    overflow-y: auto;

    .wrap {
      border-radius: 16rpx;
    }

    .title {
      font-weight: 500;
      font-size: 32rpx;
      color: #333333;
      line-height: 38rpx;
    }

    .publish-time {
      font-weight: 500;
      font-size: 24rpx;
      color: #999999;
      line-height: 28rpx;
    }
  }

  .comments {
    .mt-7 {
      margin-top: 14rpx;
    }

    .group_4 {
      margin-top: 6rpx;

      .font_2 {
        font-size: 24rpx;
        font-family: PingFang SC;
        color: #999999;
      }

      .font_3 {
        font-size: 24rpx;
        font-family: PingFang SC;
        color: #333333;
      }

      .font_4 {
        font-size: 24rpx;
        font-family: PingFang SC;
        line-height: 16.32rpx;
        color: #99999999;
      }

      .text_5 {
        margin-top: 18rpx;
        font-size: 22rpx;
      }

      .text_9 {
        margin-top: 16rpx;
        color: #000000;
        font-size: 20rpx;
        font-family: PingFang SC;
        line-height: 18.66rpx;
      }
    }

    .font_5 {
      font-size: 24rpx;
      font-family: PingFang SC;
      color: #666666;
    }

    .text_6 {
      font-size: 22rpx;
    }

    .two-level-commons {
      padding-left: 72rpx;
    }
  }

  .publish-comment {
    padding: 16rpx 32rpx;
    background-color: #fff;
    border-bottom: 2rpx solid #666666;
  }

  .publish-btn {
    background: #fcd610;
    border-radius: 80rpx;
    height: 74rpx;
    padding: 0rpx 30rpx;
    text-align: center;
    line-height: 74rpx;
    white-space: nowrap;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 32rpx;
  }
}
</style>
